package com.jike.noobmoney.mvp.view.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jike.noobmoney.R;
import com.jike.noobmoney.adapter.TaskDetailAdapter;
import com.jike.noobmoney.contants.ConstantValue;
import com.jike.noobmoney.entity.BaseEntity;
import com.jike.noobmoney.entity.TaskDetailEntity;
import com.jike.noobmoney.helper.ImageLoader;
import com.jike.noobmoney.net.RetrofitHelper;
import com.jike.noobmoney.util.AppUtils;
import com.jike.noobmoney.util.ComUtils;
import com.jike.noobmoney.util.SPUtils;
import com.jike.noobmoney.util.ToastUtils;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.wang.avi.AVLoadingIndicatorView;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPreview;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class TaskDetailActivity extends BaseActivity {

    public static final String t_id = "t_id";
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_task_img)
    ImageView ivTaskImg;
    @BindView(R.id.tv_task_title)
    TextView tvTaskTitle;
    @BindView(R.id.tv_task_remain)
    TextView tvTaskRemain;
    @BindView(R.id.tv_task_money)
    TextView tvTaskMoney;

    @BindView(R.id.tv_finishtime)
    TextView tv_finishtime;

    @BindView(R.id.tv_task_id)
    TextView tvTaskID;

    @BindView(R.id.tv_finishnum)
    TextView tv_finishnum;

    @BindView(R.id.tv_autotime)
    TextView tv_autotime;

    @BindView(R.id.tv_xsz)
    TextView tv_xsz;

    @BindView(R.id.tv_user_id)
    TextView tv_user_id;

    @BindView(R.id.tv_lsrwtgl)
    TextView tv_lsrwtgl;

    //@BindView(R.id.webview)
    //WebView webview;
    @BindView(R.id.tv_order)
    TextView tvOrder;
    @BindView(R.id.tv_img)
    ImageView tv_img;

    @BindView(R.id.avi)
    AVLoadingIndicatorView avi;
    @BindView(R.id.tv_text)
    TextView tvText;
    @BindView(R.id.ll_image)
    LinearLayout llImage;

    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.tv_type_title)
    TextView tvTypeTitle;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.iv_ecode)
    ImageView ivEcode;
    @BindView(R.id.tv_http)
    TextView tvHttp;
    @BindView(R.id.tv_right)
    TextView tv_right;

    private String taskId;
    private String userid;
    private Call<TaskDetailEntity> taskDetail;
    private Call<BaseEntity> taskOrder;
    private String ordertype = "";
    private TaskDetailAdapter adapter;
    private List<TaskDetailEntity.TaskstepBean> mData = new ArrayList<>();
    private String tasktitle;
    private String tasktext;


    @Override
    protected int layoutResID() {
        return R.layout.activity_task_detail_update;
    }

    @Override
    protected void initData() {
        if (getIntent() != null) {
            taskId = getIntent().getStringExtra(TaskDetailActivity.t_id);
        }
        userid = SPUtils.getInstance().getString(ConstantValue.SpType.userid);
        tvTitle.setText("悬赏详情");
        tv_img.setVisibility(View.VISIBLE);
        setWebsetting();
        getData();

        //adapter
        adapter = new TaskDetailAdapter(context);
        //manager
        recyclerview.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        recyclerview.setAdapter(adapter);


    }

    /**
     * 如果要全屏,重写这个方法返回false
     */
    public Boolean isfits() {
        return true;
    }

    /**
     * 如果要白色主题,重写这个方法返回false
     */
    public boolean ismain() {
        return true;
    }

    /**
     * 获取数据
     */
    private void getData() {
        avi.show();
        taskDetail = RetrofitHelper.getInstance().getTaskDetail(userid, taskId);
        taskDetail.enqueue(new Callback<TaskDetailEntity>() {
            @Override
            public void onResponse(Call<TaskDetailEntity> call, Response<TaskDetailEntity> response) {
                if (response != null) {
                    TaskDetailEntity body = response.body();
                    if (body != null) {
                        if ("100".equals(body.getCode())) {
                            setView(body);
                        } else {
                            ToastUtils.showShortToastSafe(body.getRinfo());
                        }
                    }
                    if (avi != null) {
                        avi.hide();
                    }
                }
            }

            @Override
            public void onFailure(Call<TaskDetailEntity> call, Throwable t) {
                ToastUtils.showShortToastSafe(t.getMessage());
                if (avi != null) {
                    avi.hide();
                }
            }
        });


    }

    /**
     * 设置视图
     */
    private void setView(TaskDetailEntity body) {
        TaskDetailEntity.TaskinfoBean taskinfo = body.getTaskinfo();

        if (taskinfo != null) {
            if (!TextUtils.isEmpty(taskinfo.getPicture())) {
                Glide.with(context).load(ConstantValue.IMG_BASEURL + taskinfo.getPicture()).into(ivTaskImg);
            } else {
                ivTaskImg.setImageResource(R.mipmap.ic_launcher);
            }

            tvTaskTitle.setText(TextUtils.isEmpty(taskinfo.getTaskname()) ? "小白任务" : "任务名称："+taskinfo.getTaskname());
            tvTaskRemain.setText(String.format("剩余%s份", "" + taskinfo.getLastnumber()));
            tvTaskMoney.setText(String.format("+%s元", "" + taskinfo.getMoney()));



            tvTaskID.setText("任务ID:"+taskinfo.getT_id());

            tv_finishtime.setText("完成时间："+taskinfo.limitsubmittime);

            tv_finishnum.setText("已完成："+taskinfo.getFinishnumber());

            tv_autotime.setText("审核周期："+taskinfo.autopasstime);

            tv_xsz.setText("悬赏主："+taskinfo.nick);

            tv_user_id.setText("用户ID:"+taskinfo.getU_id());
            NumberFormat num = NumberFormat.getPercentInstance();
            tv_lsrwtgl.setText("当前任务通过率："+ ComUtils.getPercent(taskinfo.finishpercent));
        }

        tasktitle = body.getTasktitle();
        tasktext = body.getTasktext();

        //tvTerminal.setText("1.支持设备:" + taskinfo.getTerminal());
        //tvUser.setText("2.适用人群:" + taskinfo.getUser());
        //tvSubmit.setText("提交方式:" + taskinfo.getSubmit());




        ordertype = body.getOrdertype();
        String order = "";
        switch (ordertype) {
            case "0":
                //未领取
                order = "领取任务";
                tvOrder.setEnabled(true);
                break;
            case "1":
                //已领取未完成
                order = "提交任务";
                tvOrder.setEnabled(true);
                break;
            case "2":
                //审核失败
                order = "审核失败";
                tvOrder.setEnabled(false);
                break;
            case "3":
                //审核中
                order = "审核中";
                tvOrder.setEnabled(false);
                break;
            case "4":
                //已完成
                order = "已完成";
                tvOrder.setEnabled(false);
                break;
        }

        tvOrder.setText(order);

//        String info = body.getTaskinfo().getInfo();
//        String cssLayout = "<style>*{padding: 0;margin: 0}#webview_content_wrapper{margin: 0px 0px 0 0px;} p{color: #333333;line-height: 2em;font-size:14px;opacity: 1;} img {margin-top: 13px;margin-bottom: 15px;max-width:100%;height:auto;;}</style>";
//        String htmlModify = info.replaceAll("<br/>", "");
//        String htmlcontent = cssLayout + "<body><div id='webview_content_wrapper'>" + htmlModify + "</div></body>";
//        webview.loadDataWithBaseURL(null, htmlcontent, "text/html", "utf-8", null);

        tvText.setTextIsSelectable(true);
        tvText.setText(taskinfo.getText());

//        String image = taskinfo.getImage();
//        String[] result = image.split(",");
//        for (int i = 0; i < result.length; i++) {
//            String s = result[i];
//            String url = ConstantValue.IMG_BASEURL + s;
//            addImg(url);
//            Imageurls.add(url);
//        }




        int opentype = taskinfo.getOpentype(); //1二维码  2链接
        String openurl = taskinfo.getOpenurl();
        if (opentype == 1) {
            tvType.setText("二维码");
            ivEcode.setVisibility(View.VISIBLE);
            tvHttp.setVisibility(View.GONE);
            Glide.with(this).load(ConstantValue.IMG_BASEURL_QR_CODE + openurl).into(ivEcode);
        } else if (opentype == 2) {
            tvType.setText("链接");
            ivEcode.setVisibility(View.GONE);
            tvHttp.setVisibility(View.VISIBLE);
            tvHttp.setText(openurl);
        } else {
            tvTypeTitle.setVisibility(View.GONE);
            tvType.setVisibility(View.GONE);
            ivEcode.setVisibility(View.GONE);
            tvHttp.setVisibility(View.GONE);
        }

        ivEcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<String> photoPaths = new ArrayList<>();
                photoPaths.add(ConstantValue.IMG_BASEURL_QR_CODE + openurl);
                PhotoPreview.builder()
                        .setPhotos(photoPaths)
                        .setCurrentItem(0)
                        .setShowDeleteButton(true)
                        .start((Activity) context);
            }
        });


        //步骤
        List<TaskDetailEntity.TaskstepBean> taskstep = body.getTaskstep();
        if (taskstep != null) {
            mData.clear();
            mData.addAll(taskstep);
        }
        adapter.refresh(mData);


    }

    private ArrayList<String> Imageurls = new ArrayList<>();

    private void addImg(String url) {
        ImageView newImg = new ImageView(this);
        //设置想要的图片，相当于android:src="@drawable/image"
        //newImg.setImageResource(R.mipmap.ic_launcher);
        ImageLoader.displayImage(this, url, newImg);

        //设置子控件在父容器中的位置布局，wrap_content,match_parent
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        // 也可以自己想要的宽度，参数（int width, int height）均表示px
        // 如dp单位，首先获取屏幕的分辨率在求出密度，根据屏幕ppi=160时，1px=1dp
        //则公式为 dp * ppi / 160 = px ——> dp * dendity = px
        //如设置为48dp：1、获取屏幕的分辨率 2、求出density 3、设置
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        float density = displayMetrics.density;
        LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(
                (int) (48 * density),
                (int) (48 * density));
        //相当于android:layout_marginLeft="8dp"
        params.leftMargin = 20;
        params.rightMargin = 20;
        params.topMargin = 20;
        //addView(View child)，默认往已有的view后面添加，后插入，不设置布局params,默认wrap_content
        //llImage.addView(newImg);
        //addView(View child, LayoutParams params)，往已有的view后面添加，后插入,并设置布局
        llImage.addView(newImg, params);

    }

    @SuppressWarnings("deprecation")
    @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
    private void setWebsetting() {
//        WebSettings webSettings = webview.getSettings();
//        webSettings.setJavaScriptEnabled(true);
//        webview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
//        webSettings.setDefaultTextEncodingName("UTF-8");
//        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
//        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
//        webSettings.setSupportMultipleWindows(true);
//        webSettings.setBuiltInZoomControls(false);
//        webSettings.setSupportZoom(false);
//        webSettings.setDisplayZoomControls(false);
//        webSettings.setPluginState(WebSettings.PluginState.ON);
//        webSettings.setDomStorageEnabled(true);
//        webSettings.setLoadsImagesAutomatically(true);
//        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
//
//        webview.clearCache(true);
//        webview.clearHistory();
    }

    @OnClick({R.id.iv_back, R.id.tv_order, R.id.ll_image, R.id.tv_right,R.id.tv_img})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_order:
                if (tvOrder.isEnabled()) {
                    switch (ordertype) {
                        case "0":
                            if (AppUtils.isFastClick()) {
                                ToastUtils.showShortToastSafe("操作有点频繁,稍后重试");
                                return;
                            }
                            //未领取  领取任务
                            getTaskOrder();
                            break;
                        case "1":
                            if (AppUtils.isFastClick()) {
                                ToastUtils.showShortToastSafe("操作有点频繁,稍后重试");
                                return;
                            }
                            //已领取未完成  提交任务
                            confirmOrder();
                            break;
                        default:
                            break;
                    }
                    ToastUtils.showShortToastSafe(tvOrder.getText().toString().trim());
                }
                break;
            case R.id.ll_image:

                break;
            case R.id.tv_img:
                if (AppUtils.isFastClick()) {
                    ToastUtils.showShortToastSafe("操作有点频繁,稍后重试");
                    return;
                }
                share();
                break;
        }
    }

    /**
     * 点击分享
     */
    public void share() {
        String url = "http://xiaobai.jikewangluo.cn/renwu/shareindex?t_id=" + taskId;
        UMWeb web = new UMWeb(url);
        web.setTitle(TextUtils.isEmpty(tasktitle) ? "小白赚钱" : tasktitle);
        web.setThumb(new UMImage(context, R.mipmap.ic_launcher));
        web.setDescription(TextUtils.isEmpty(tasktext) ? getString(R.string.text_yaoqing1) : tasktext);
        ShareAction shareAction = new ShareAction(this);
        shareAction.withMedia(web);
        shareAction.setDisplayList(SHARE_MEDIA.QZONE, SHARE_MEDIA.QQ, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE);
        shareAction.setCallback(shareListener);
        shareAction.open();
    }

    private UMShareListener shareListener = new UMShareListener() {

        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            ToastUtils.showShortToastSafe("分享成功了");
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            ToastUtils.showShortToastSafe("分享失败了");

        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            ToastUtils.showShortToastSafe("分享取消了");
        }
    };


    /**
     * 领取任务
     */
    public void getTaskOrder() {
        taskOrder = RetrofitHelper.getInstance().getTaskOrder(userid, taskId);
        taskOrder.enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                if (response != null) {
                    BaseEntity body = response.body();
                    if (body != null) {
                        if ("100".equals(body.getCode())) {
                            //领取成功  跳转到我的任务页面
                            startActivity(new Intent(TaskDetailActivity.this, MyTaskActivity.class));
                            finish();
                        } else {
                            ToastUtils.showShortToastSafe(body.getRinfo());
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                ToastUtils.showLongToast(t.getMessage());
            }
        });
    }

    /**
     * 提交任务
     */
    public void confirmOrder() {
        //Intent intent = new Intent(context, UnFinishTaskActivity.class);
        //intent.putExtra(UnFinishTaskActivity.t_id, "" + taskId);
        //startActivityForResult(intent, 100);
        //---------这里拿不到o_id  暂时先跳到我的任务页面
        startActivity(new Intent(TaskDetailActivity.this, MyTaskActivity.class));
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (taskDetail != null) {
            taskDetail.cancel();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
